<template>
  <div class="employee-archive-box">
    <el-form :model="form" :rules="rules" ref="formRef" label-width="110px" class="archive-form">
      <el-row :gutter="24">
        <el-col :span="8">
          <el-form-item label="员工姓名" prop="name">
            <el-input v-model="form.name" placeholder="请输入员工姓名" />
          </el-form-item>
          <el-form-item label="性别" prop="gender">
            <el-select v-model="form.gender" placeholder="请选择性别">
              <el-option label="男" value="男" />
              <el-option label="女" value="女" />
            </el-select>
          </el-form-item>
          <el-form-item label="身份证" prop="idCard">
            <el-input v-model="form.idCard" placeholder="请输入身份证号" />
          </el-form-item>
          <el-form-item label="在职状态" prop="jobStatus">
            <el-select v-model="form.jobStatus" placeholder="请选择在职状态">
              <el-option label="在职" value="在职" />
              <el-option label="离职" value="离职" />
            </el-select>
          </el-form-item>
          <el-form-item label="入职日期" prop="entryDate">
            <el-date-picker v-model="form.entryDate" type="date" placeholder="选择日期" style="width: 100%" />
          </el-form-item>
          <el-form-item label="合同到期" prop="contractEnd">
            <el-date-picker v-model="form.contractEnd" type="date" placeholder="选择日期" style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="用户工号" prop="jobNumber">
            <el-input v-model="form.jobNumber" placeholder="保存时自动生成" disabled />
          </el-form-item>
          <el-form-item label="婚姻状态" prop="maritalStatus">
            <el-select v-model="form.maritalStatus" placeholder="请选择婚姻状态">
              <el-option label="未婚" value="未婚" />
              <el-option label="已婚" value="已婚" />
            </el-select>
          </el-form-item>
          <el-form-item label="离职日期" prop="leaveDate">
            <el-date-picker v-model="form.leaveDate" type="date" placeholder="选择日期" style="width: 100%" />
          </el-form-item>
          <el-form-item label="合同到期" prop="contractEnd2">
            <el-date-picker v-model="form.contractEnd2" type="date" placeholder="选择日期" style="width: 100%" />
          </el-form-item>
          <el-form-item label="所属部门" prop="department">
            <el-input v-model="form.departmentFullName" placeholder="请选择部门" readonly @click="showDeptDialog = true" style="width: 70%; display: inline-block; margin-right: 8px;" />
            <el-button type="primary" @click="showDeptDialog = true">选择部门</el-button>
          </el-form-item>
          <el-form-item label="工作照片">
            <el-upload
              class="avatar-uploader"
              action="#"
              :show-file-list="false"
              :on-change="handleAvatarChange"
            >
              <img v-if="form.avatarUrl" :src="form.avatarUrl" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="钉钉UserId" prop="dingUserId">
            <el-input v-model="form.dingUserId" placeholder="请输入钉钉UserId" />
          </el-form-item>
          <el-form-item label="钉钉企业ID" prop="dingCorpId">
            <el-input v-model="form.dingCorpId" placeholder="请输入钉钉企业ID" />
          </el-form-item>
          <el-form-item label="开户银行" prop="bankName">
            <el-input v-model="form.bankName" placeholder="请输入开户银行" />
          </el-form-item>
          <el-form-item label="银行账号" prop="bankAccount">
            <el-input v-model="form.bankAccount" placeholder="请输入银行账号" />
          </el-form-item>
          <el-form-item label="工作号码" prop="workNumber">
            <el-input v-model="form.workNumber" placeholder="请输入工作号码" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-tabs type="card" class="archive-tabs">
        <el-tab-pane label="基本信息">
          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item label="民族" prop="nation">
                <el-input v-model="form.nation" placeholder="请选择民族" readonly @click="showNationDialog = true" style="width: 70%; display: inline-block; margin-right: 8px;" />
                <el-button type="primary" @click="showNationDialog = true">选择民族</el-button>
              </el-form-item>
              <el-form-item label="毕业院校" prop="school">
                <el-input v-model="form.school" placeholder="请输入毕业院校" />
              </el-form-item>
              <el-form-item label="最高学历" prop="education">
                <el-select v-model="form.education" placeholder="请选择学历">
                  <el-option label="本科" value="本科" />
                  <el-option label="硕士" value="硕士" />
                  <el-option label="博士" value="博士" />
                  <el-option label="大专" value="大专" />
                  <el-option label="高中及以下" value="高中及以下" />
                </el-select>
              </el-form-item>
              <el-form-item label="紧急联系人" prop="emergencyContact">
                <el-input v-model="form.emergencyContact" placeholder="请输入紧急联系人" />
              </el-form-item>
              <el-form-item label="紧急联系电话" prop="emergencyPhone">
                <el-input v-model="form.emergencyPhone" placeholder="请输入紧急联系电话" />
              </el-form-item>
              <el-form-item label="身份证正面">
                <el-upload class="upload-demo" action="#" :show-file-list="false" :on-change="handleIdFrontChange">
                  <img v-if="form.idFrontUrl" :src="form.idFrontUrl" class="avatar" />
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="省份" prop="province">
                <el-input v-model="form.province" placeholder="请选择省份" readonly @click="showProvinceDialog = true" style="width: 70%; display: inline-block; margin-right: 8px;" />
                <el-button type="primary" @click="showProvinceDialog = true">选择省份</el-button>
              </el-form-item>
              <el-form-item label="市" prop="city">
                <el-input v-model="form.city" placeholder="请选择市" readonly @click="showCityDialog = true" style="width: 70%; display: inline-block; margin-right: 8px;" />
                <el-button type="primary" @click="showCityDialog = true">选择市</el-button>
              </el-form-item>
              <el-form-item label="区县" prop="district">
                <el-input v-model="form.district" placeholder="请选择区县" readonly @click="showDistrictDialog = true" style="width: 70%; display: inline-block; margin-right: 8px;" />
                <el-button type="primary" @click="showDistrictDialog = true">选择区县</el-button>
              </el-form-item>
              <el-form-item label="移动电话" prop="mobile">
                <el-input v-model="form.mobile" placeholder="请输入移动电话" />
              </el-form-item>
              <el-form-item label="电子邮箱" prop="email">
                <el-input v-model="form.email" placeholder="请输入电子邮箱" />
              </el-form-item>
              <el-form-item label="身份证反面">
                <el-upload class="upload-demo" action="#" :show-file-list="false" :on-change="handleIdBackChange">
                  <img v-if="form.idBackUrl" :src="form.idBackUrl" class="avatar" />
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="联系地址" prop="address">
                <el-input v-model="form.address" type="textarea" placeholder="请输入联系地址" />
              </el-form-item>
              <el-form-item label="职称" prop="title">
                <el-input v-model="form.title" placeholder="请输入职称" />
              </el-form-item>
              <el-form-item label="学位证书">
                <el-upload class="upload-demo" action="#" :show-file-list="false" :on-change="handleDegreeChange">
                  <img v-if="form.degreeUrl" :src="form.degreeUrl" class="avatar" />
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </el-form-item>
              <el-form-item label="其他证书">
                <el-upload class="upload-demo" action="#" :show-file-list="false" :on-change="handleOtherCertChange">
                  <img v-if="form.otherCertUrl" :src="form.otherCertUrl" class="avatar" />
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="英文名" prop="englishName">
                <el-input v-model="form.englishName" placeholder="请输入英文名" />
              </el-form-item>
              <el-form-item label="部门全称" prop="departmentFullName">
                <el-input v-model="form.departmentFullName" placeholder="请输入部门全称" />
              </el-form-item>
              <el-form-item label="描述" prop="description">
                <el-input v-model="form.description" placeholder="请输入描述" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-tab-pane>
        <!-- 你可以继续扩展自定义操作日志、其他tab等 -->
      </el-tabs>
      <el-form-item style="margin-top: 32px; text-align: center; width: 100%">
        <el-button type="primary" @click="onSubmit">提交</el-button>
        <el-button @click="onReset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 部门选择弹窗 -->
    <el-dialog v-model="showDeptDialog" title="选择所属部门" width="500px" @close="onDeptDialogClose">
      <el-input v-model="deptSearch" placeholder="搜索部门名称/编码" clearable @input="fetchDepartmentList" style="margin-bottom: 16px;" />
      <el-table :data="filteredDeptList" style="width: 100%;" height="300">
        <el-table-column prop="部门全称" label="部门全称" />
        <el-table-column prop="名称" label="名称" />
        <el-table-column prop="部门编码" label="部门编码" />
        <el-table-column label="操作" width="80">
          <template #default="scope">
            <el-button type="primary" size="small" @click="selectDepartment(scope.row)">选择</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 民族选择弹窗 -->
    <el-dialog v-model="showNationDialog" title="选择民族" width="400px" @close="onNationDialogClose">
      <el-input v-model="nationSearch" placeholder="搜索民族" clearable @input="fetchNationList" style="margin-bottom: 16px;" />
      <el-table :data="filteredNationList" style="width: 100%;" height="300">
        <el-table-column prop="名称" label="民族名称" />
        <el-table-column prop="编码" label="民族编码" />
        <el-table-column label="操作" width="80">
          <template #default="scope">
            <el-button type="primary" size="small" @click="selectNation(scope.row)">选择</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 省份选择弹窗 -->
    <el-dialog v-model="showProvinceDialog" title="选择省份" width="400px" @close="onProvinceDialogClose">
      <el-input v-model="provinceSearch" placeholder="搜索省份" clearable @input="fetchProvinceList" style="margin-bottom: 16px;" />
      <el-table :data="filteredProvinceList" style="width: 100%;" height="300">
        <el-table-column prop="名称" label="省份名称" />
        <el-table-column prop="编码" label="省份编码" />
        <el-table-column label="操作" width="80">
          <template #default="scope">
            <el-button type="primary" size="small" @click="selectProvince(scope.row)">选择</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 市选择弹窗 -->
    <el-dialog v-model="showCityDialog" title="选择市" width="400px" @close="onCityDialogClose">
      <el-input v-model="citySearch" placeholder="搜索市" clearable @input="fetchCityList" style="margin-bottom: 16px;" />
      <el-table :data="filteredCityList" style="width: 100%;" height="300">
        <el-table-column prop="名称" label="市区名称" />
        <el-table-column prop="编码" label="市区编码" />
        <el-table-column label="操作" width="80">
          <template #default="scope">
            <el-button type="primary" size="small" @click="selectCity(scope.row)">选择</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 区县选择弹窗 -->
    <el-dialog v-model="showDistrictDialog" title="选择区县" width="400px" @close="onDistrictDialogClose">
      <el-input v-model="districtSearch" placeholder="搜索区县" clearable @input="fetchDistrictList" style="margin-bottom: 16px;" />
      <el-table :data="filteredDistrictList" style="width: 100%;" height="300">
        <el-table-column prop="名称" label="县区名称" />
        <el-table-column prop="编码" label="县区编码" />
        <el-table-column label="操作" width="80">
          <template #default="scope">
            <el-button type="primary" size="small" @click="selectDistrict(scope.row)">选择</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
import { onMounted, ref, computed, watch, nextTick } from 'vue';
import { useRoute } from 'vue-router'; // 新增

import { ElMessage, ElMessageBox } from 'element-plus';
import { createEmployee, amendEmployee, employeeArchiveQuery, getEmployeeGroupList, getDepartmentList, getEthnicGroupList, getProvinceList, getCityDistrictList, getCountyDistrictList } from '@/api/api';
import axios from 'axios'; // 新增

const formRef = ref();
const form = ref({
  name: '', gender: '', idCard: '', jobStatus: '', entryDate: '', contractEnd: '',
  jobNumber: '', maritalStatus: '', leaveDate: '', contractEnd2: '', department: '', avatarUrl: '',
  dingUserId: '', dingCorpId: '', bankName: '', bankAccount: '', workNumber: '',
  nation: '', school: '', education: '', emergencyContact: '', emergencyPhone: '', idFrontUrl: '',
  province: '', city: '', district: '', mobile: '', email: '', idBackUrl: '', address: '', title: '', degreeUrl: '', otherCertUrl: '',
  creatorStaffNumber: '', // 创建人工号
  auditStaffNumber: '', // 审核人工号
  modifierStaffNumber: '', // 修改人工号
  englishName: '', // 英文名
  departmentFullName: '', // 部门全称
  description: '' // 描述
});
const rules = {
  name: [{ required: true, message: '请输入员工姓名', trigger: 'blur' }],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
  idCard: [{ required: true, message: '请输入身份证号', trigger: 'blur' }],
  jobStatus: [{ required: true, message: '请选择在职状态', trigger: 'change' }],
  entryDate: [{ required: true, message: '请选择入职日期', trigger: 'change' }],
  department: [{ required: true, message: '请输入部门名称', trigger: 'blur' }],
  nation: [{ required: true, message: '请选择民族', trigger: 'blur' }],
  province: [{ required: true, message: '请输入省份', trigger: 'blur' }],
  city: [{ required: true, message: '请输入市', trigger: 'blur' }],
  district: [{ required: true, message: '请输入区县', trigger: 'blur' }],
  creatorStaffNumber: [{ required: true, message: '请输入创建人工号', trigger: 'blur' }],
  auditStaffNumber: [{ required: true, message: '请输入审核人工号', trigger: 'blur' }],
  modifierStaffNumber: [{ required: true, message: '请输入修改人工号', trigger: 'blur' }],
  englishName: [{ required: false, message: '请输入英文名', trigger: 'blur' }],
  departmentFullName: [{ required: false, message: '请输入部门全称', trigger: 'blur' }],
  description: [{ required: false, message: '请输入描述', trigger: 'blur' }],
  leaveDate: [{ required: true, message: '请选择离职日期', trigger: 'change' }],
};

function handleAvatarChange(file) {
  // 这里可接入上传接口，示例直接用本地预览
  const reader = new FileReader();
  reader.onload = e => { form.value.avatarUrl = e.target.result; };
  reader.readAsDataURL(file.raw);
}
function handleIdFrontChange(file) {
  const reader = new FileReader();
  reader.onload = e => { form.value.idFrontUrl = e.target.result; };
  reader.readAsDataURL(file.raw);
}
function handleIdBackChange(file) {
  const reader = new FileReader();
  reader.onload = e => { form.value.idBackUrl = e.target.result; };
  reader.readAsDataURL(file.raw);
}
function handleDegreeChange(file) {
  const reader = new FileReader();
  reader.onload = e => { form.value.degreeUrl = e.target.result; };
  reader.readAsDataURL(file.raw);
}
function handleOtherCertChange(file) {
  const reader = new FileReader();
  reader.onload = e => { form.value.otherCertUrl = e.target.result; };
  reader.readAsDataURL(file.raw);
}

function getCurrentUserStaffNumber() {
  // 优先取员工编号，没有则取登录账号
  return localStorage.getItem('员工编号') || localStorage.getItem('登录账号') || '';
}
function getCurrentUserId() {
  return localStorage.getItem('员工ID') || '';
}
function getCurrentUserName() {
  return localStorage.getItem('员工姓名') || '';
}
function getCurrentToken() {
  return localStorage.getItem('Token') || '';
}

// 生成唯一6位数字工号（本地简单实现，实际唯一性建议后端校验）
function generateStaffNumber() {
  let num;
  do {
    num = Math.floor(100000 + Math.random() * 900000).toString();
  } while (num === form.value.jobNumber); // 简单防止和当前重复
  return num;
}

// 日期转ISO字符串
function toISODate(val) {
  if (!val) return "";
  const d = new Date(val);
  return isNaN(d.getTime()) ? "" : d.toISOString();
}

// 新增：表单数据转接口参数
function mapFormToModel(form) {
  if (!form.jobNumber) {
    form.jobNumber = generateStaffNumber();
  }
  return {
    FID: form.FID ? String(form.FID) : '0', // 关键：提交时带上 FID，且为字符串
    FName: form.name || '',
    FStaffNumber: form.jobNumber || generateStaffNumber(),
    FMobile: form.mobile || '',
    FEmail: form.email || '',
    FDescription: form.description || '',
    FAddress: form.address || '',
    FJoinDate: toISODate(form.entryDate),
    FGender: form.gender === '男' ? '0' : form.gender === '女' ? '1' : form.gender || '',
    FIdCard: form.idCard || '',
    FInEmploymentStatus: form.jobStatus || '',
    FContractSigning: toISODate(form.entryDate),
    FMaritalStatus: form.maritalStatus || '',
    FEnglishName: form.englishName || '',
    FContractExpiration: toISODate(form.contractEnd || form.contractEnd2),
    FDepartmentName: form.department || '',
    FDingTalkUserId: form.dingUserId || '',
    FDingTalkEnterpriseId: form.dingCorpId || '',
    FDepartmentFullName: form.departmentFullName || '',
    FEthnicGroup: form.nationCode || '',
    FGraduationUniversity: form.school || '',
    FHighestEducation: form.education || '',
    FEmergencyContact: form.emergencyContact || '',
    FEmergencyContactNumber: form.emergencyPhone || '',
    FProvinceName: form.provinceCode || '',
    FCity: form.cityCode || '',
    FCountyArea: form.districtCode || '',
    FOpeningBank: form.bankName || '',
    FBankCardNumber: form.bankAccount || '',
    FWorkPhone: form.workNumber || '',
    FCreatorUserIdNew: getCurrentUserStaffNumber(),
    FAuditUserIdNew: getCurrentUserStaffNumber(),
    FModifierUserIdNew: getCurrentUserStaffNumber(),
    FLeaveDate: toISODate(form.leaveDate),
    sys_token: getCurrentToken()
  };
}

// 新增：保存员工档案
async function saveEmployee() {
  const params = mapFormToModel(form.value);
  try {
    // 检查 createEmployee 的 API 路径和参数
    // 404 说明接口地址不对或者后端没部署该接口
    // 1. 检查 src/api/api.js 里的 createEmployee 方法，确认接口路径是否正确
    // 2. 确认后端服务 http://192.168.6.240:11000/employee/employee/createEmployee 是否存在
    // 3. 如果接口路径有变化，需同步前端和后端接口地址
    await createEmployee(params); // 使用api方法
    ElMessage.success('保存成功');
  } catch (e) {
    // 404 错误时给出详细提示
    if (e?.response?.status === 404) {
      ElMessage.error('接口未找到（404），请联系后端确认接口地址是否正确');
    } else {
      ElMessage.error('保存失败');
    }
  }
}

function onSubmit() {
  formRef.value.validate(valid => {
    if (!valid) return;
    const params = mapFormToModel(form.value);
    const confirmMsg = type.value === 'edit' ? '是否确认修改？' : '是否确认提交？';
    ElMessageBox.confirm(
      confirmMsg,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(() => {
      if (type.value === 'edit') {
        amendEmployee(params).then(() => {
          ElMessage.success('修改成功');
        }).catch(() => {
          ElMessage.error('修改失败');
        });
      } else {
        createEmployee(params).then(() => {
          ElMessage.success('保存成功');
        }).catch(() => {
          ElMessage.error('保存失败');
        });
      }
    }).catch(() => {
      ElMessage.info('已取消提交');
    });
  });
}
function onReset() {
  formRef.value.resetFields();
}

const showDeptDialog = ref(false);
const deptSearch = ref("");
const deptList = ref([]);
const filteredDeptList = computed(() => {
  if (!deptSearch.value) return deptList.value;
  return deptList.value.filter(item =>
    (item['部门编码'] && item['部门编码'].includes(deptSearch.value)) ||
    (item['部门全称'] && item['部门全称'].includes(deptSearch.value))
  );
});
const departmentLoading = ref(false);

// 获取部门列表
async function fetchDepartmentList() {
  departmentLoading.value = true;
  try {
    const res = await getDepartmentList({
      departmentName: deptSearch.value
    });
    // 兼容后端返回结构，支持 res.data.data 或 res.data
    if (Array.isArray(res?.data?.data)) {
      deptList.value = res.data.data;
    } else if (Array.isArray(res?.data)) {
      deptList.value = res.data;
    } else {
      deptList.value = [];
    }
  } catch (e) {
    deptList.value = [];
  } finally {
    departmentLoading.value = false;
  }
}

// 选择部门
function selectDepartment(row) {
  form.value.department = row["部门编码"];
  form.value.departmentFullName = row["部门全称"] || row["名称"];
  showDeptDialog.value = false;
}

// 关闭部门选择弹窗
function onDeptDialogClose() {
  deptSearch.value = "";
}

// 打开弹窗时自动加载部门
watch(showDeptDialog, (val) => {
  if (val) fetchDepartmentList();
});

// 新增：民族相关变量和方法
const showNationDialog = ref(false);
const nationSearch = ref("");
const nationList = ref([]);
const filteredNationList = computed(() => {
  if (!nationSearch.value) return nationList.value;
  return nationList.value.filter(item =>
    (item['民族名称'] && item['民族名称'].includes(nationSearch.value))
  );
});
const nationLoading = ref(false);

// 获取民族列表
async function fetchNationList() {
  nationLoading.value = true;
  try {
    const res = await getEthnicGroupList({ nationName: nationSearch.value });
    nationList.value = Array.isArray(res?.data?.data) ? res.data.data : [];
  } catch (e) {
    nationList.value = [];
  } finally {
    nationLoading.value = false;
  }
}

// 选择民族
function selectNation(row) {
  form.value.nation = row["名称"]; // 输入框展示民族名称
  form.value.nationCode = row["编码"]; // 保存时用民族编码
  showNationDialog.value = false;
}

// 关闭民族选择弹窗
function onNationDialogClose() {
  nationSearch.value = "";
}

// 打开弹窗时自动加载民族
watch(showNationDialog, (val) => {
  if (val) fetchNationList();
});

// 新增：省份相关变量和方法
const showProvinceDialog = ref(false);
const provinceSearch = ref("");
const provinceList = ref([]);
const filteredProvinceList = computed(() => {
  if (!provinceSearch.value) return provinceList.value;
  return provinceList.value.filter(item =>
    (item['名称'] && item['名称'].includes(provinceSearch.value))
  );
});
const provinceLoading = ref(false);

async function fetchProvinceList() {
  provinceLoading.value = true;
  try {
    const res = await getProvinceList({ provinceName: provinceSearch.value });
    provinceList.value = Array.isArray(res?.data?.data) ? res.data.data : [];
  } catch (e) {
    provinceList.value = [];
  } finally {
    provinceLoading.value = false;
  }
}
function selectProvince(row) {
  form.value.province = row['名称']; // 输入框展示名称
  form.value.provinceCode = row['编码']; // 保存时用编码
  showProvinceDialog.value = false;
  // 清空市、区县
  form.value.city = '';
  form.value.cityCode = '';
  form.value.district = '';
  form.value.districtCode = '';
}
function onProvinceDialogClose() {
  provinceSearch.value = '';
}
watch(showProvinceDialog, (val) => { if (val) fetchProvinceList(); });

// 市弹窗相关
const showCityDialog = ref(false);
const citySearch = ref("");
const cityList = ref([]);
const filteredCityList = computed(() => {
  if (!citySearch.value) return cityList.value;
  return cityList.value.filter(item =>
    (item['名称'] && item['名称'].includes(citySearch.value))
  );
});
const cityLoading = ref(false);

async function fetchCityList() {
  cityLoading.value = true;
  try {
    const res = await getCityDistrictList({ cityName: citySearch.value, provinceCode: form.value.provinceCode });
    cityList.value = Array.isArray(res?.data?.data) ? res.data.data : [];
  } catch (e) {
    cityList.value = [];
  } finally {
    cityLoading.value = false;
  }
}
function selectCity(row) {
  form.value.city = row['名称'];
  form.value.cityCode = row['编码'];
  showCityDialog.value = false;
  // 清空区县
  form.value.district = '';
  form.value.districtCode = '';
}
function onCityDialogClose() {
  citySearch.value = '';
}
watch(showCityDialog, (val) => { if (val) fetchCityList(); });

// 区县弹窗相关
const showDistrictDialog = ref(false);
const districtSearch = ref("");
const districtList = ref([]);
const filteredDistrictList = computed(() => {
  if (!districtSearch.value) return districtList.value;
  return districtList.value.filter(item =>
    (item['名称'] && item['名称'].includes(districtSearch.value))
  );
});
const districtLoading = ref(false);

async function fetchDistrictList() {
  districtLoading.value = true;
  try {
    const res = await getCountyDistrictList({ countyName: districtSearch.value, cityCode: form.value.cityCode });
    districtList.value = Array.isArray(res?.data?.data) ? res.data.data : [];
  } catch (e) {
    districtList.value = [];
  } finally {
    districtLoading.value = false;
  }
}
function selectDistrict(row) {
  form.value.district = row['名称'];
  form.value.districtCode = row['编码'];
  showDistrictDialog.value = false;
}
function onDistrictDialogClose() {
  districtSearch.value = '';
}
watch(showDistrictDialog, (val) => { if (val) fetchDistrictList(); });

// 省市区code辅助方法（如接口返回有编码字段可补充）
function getProvinceCode(name) {
  const item = provinceList.value.find(i => i['省份名称'] === name);
  return item ? item['省份编码'] : '';
}
function getCityCode(name) {
  const item = cityList.value.find(i => i['市区名称'] === name);
  return item ? item['市区编码'] : '';
}

const route = useRoute();
const type = ref(route.query.type || 'add');

function mapRouteQueryToForm(query) {
  return {
    jobNumber: query['员工工号'] || '',
    name: query['员工姓名'] || '',
    gender: query['性别'] === '0' ? '男' : query['性别'] === '1' ? '女' : query['性别'] || '',
    idCard: query['身份证'] || '',
    jobStatus: query['在职状态'] || '',
    entryDate: query['入职日期'] || '',
    contractEnd: query['合同到期'] || '',
    departmentFullName: query['部门全称'] || '',
    mobile: query['移动电话'] || '',
    email: query['电子邮箱'] || '',
    description: query['描述'] || '',
    // 其他字段按需补充
  };
}

function mapEmployeeDataToForm(data) {
  return {
    FID: data.FID ? String(data.FID) : '', // 关键：回显时带上 FID，且为字符串
    jobNumber: data["员工工号"] || data.FStaffNumber || '',
    name: data["员工姓名"] || data.FName || '',
    gender: data["性别"] === '0' ? '男' : data["性别"] === '1' ? '女' : data["性别"] || '',
    idCard: data["身份证"] || data.FIdCard || '',
    jobStatus: data["在职状态"] || data.FInEmploymentStatus || '',
    entryDate: data["入职日期"] || data.FJoinDate || '',
    contractEnd: data["合同到期"] || data.FContractExpiration || '',
    departmentFullName: data["部门全称"] || data.FDepartmentFullName || '',
    mobile: data["移动电话"] || data.FMobile || '',
    email: data["电子邮箱"] || data.FEmail || '',
    description: data["描述"] || data.FDescription || '',
    maritalStatus: data["婚姻状态"] || data.FMaritalStatus || '',
    leaveDate: data["离职日期"] || data.FLeaveDate || '',
    contractEnd2: data["合同到期"] || data.FContractExpiration || '',
    department: data["所属部门"] || data.FDepartmentName || '',
    avatarUrl: data["工作照"] || data.FAvatarUrl || '',
    dingUserId: data["钉钉UserId"] || data.FDingTalkUserId || '',
    dingCorpId: data["钉钉企业ID"] || data.FDingTalkEnterpriseId || '',
    bankName: data["开户银行"] || data.FOpeningBank || '',
    bankAccount: data["银行卡号"] || data.FBankCardNumber || '',
    workNumber: data["工作号码"] || data.FWorkPhone || '',
    nation: data["民族"] || data.FEthnicGroup || '',
    school: data["毕业院校"] || data.FGraduationUniversity || '',
    education: data["最高学历"] || data.FHighestEducation || '',
    emergencyContact: data["紧急联系人"] || data.FEmergencyContact || '',
    emergencyPhone: data["紧急联系电话"] || data.FEmergencyContactNumber || '',
    idFrontUrl: data["身份证正面"] || data.FIdFrontUrl || '',
    province: data["省份"] || data.FProvinceName || '',
    city: data["市"] || data.FCity || '',
    district: data["区县"] || data.FCountyArea || '',
    idBackUrl: data["身份证反面"] || data.FIdBackUrl || '',
    address: data["联系地址"] || data.FAddress || '',
    title: data["职称"] || data.FTitle || '',
    degreeUrl: data["学位证书"] || data.FDegreeUrl || '',
    otherCertUrl: data["其他证书"] || data.FOtherCertUrl || '',
    creatorStaffNumber: data["创建人"] || data.FCreatorUserIdNew || '',
    auditStaffNumber: data["审核人"] || data.FAuditUserIdNew || '',
    modifierStaffNumber: data["修改人"] || data.FModifierUserIdNew || '',
    englishName: data["英文名"] || data.FEnglishName || '',
    // 其他字段可继续补充
  };
}

onMounted(() => {
  // 打印看看有没有带过来
  console.log('路由参数:', route.query);
  // 字段映射并合并到表单，实现回显
  Object.assign(form.value, mapRouteQueryToForm(route.query));
  if (type.value === 'edit' && route.query.fid) {
    const params = {
      p: { page_number: 1, page_size: 100 },
      e: { where: false, fid: route.query.fid }
    };
    employeeArchiveQuery(params).then(res => {
      const data = Array.isArray(res?.data?.data) ? res.data.data[0] : null;
      if (data) {
        Object.assign(form.value, mapEmployeeDataToForm(data));
      }
    });
  }
  fetchDepartmentList();
});
</script>

<style lang="scss" scoped>
.employee-archive-box {
  background: #fafbfc;
  padding: 24px;
  
}
.archive-form {
  background: #fff;
  padding: 24px;
  border-radius: 8px;
}
.avatar-uploader .avatar,
.upload-demo .avatar {
  width: 100px;
  height: 100px;
  display: block;
  border-radius: 6px;
}
.avatar-uploader-icon {
  font-size: 32px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
}
.archive-tabs {
  margin-top: 24px;
}
</style>